package gameLogic

import (
	"net"
	"server_cluster/common/config"
	"server_cluster/common/logger"
	"server_cluster/common/myepoll"
	"server_cluster/common/mysock"
	"server_cluster/common/protoc/pb"
	"server_cluster/common/sharedb"
	"server_cluster/gate/db"
	"server_cluster/gate/gate_config"
	"server_cluster/gate/sharemem"

	"google.golang.org/protobuf/proto"
)

func UserCheck() {
	//  return
	var myshm = sharemem.Myshm
	for _, v := range sharemem.GetUserMap() {
		if myshm.Time_now-v.AliveTime > config.USER_TIME_MAX {
			v.Clean_user()
		}
	}
}

func Login(conn net.Conn, mybuf *mysock.SockBuf, shm_user **sharemem.User, fd int32) {
	// 获取前端数据
	createreq := pb.CS_Login{}
	err := proto.Unmarshal(mybuf.Data[mysock.HEAD_LEN:mysock.HEAD_LEN+mybuf.Data_length], &createreq)
	if err != nil {
		logger.Error("parse CS_FightAction error:%v", err)
		return
	}
	uid := createreq.GetUid()
	token := createreq.GetToken()
	// logger.Info("uid=%d token=%s,err=%v",uid,token,err)
	// logger.Info("fight_data = %v",fight_data)
	logger.Warn("Login uid = %d token = %s", uid, token)

	mybuf.Command = config.SC_Login
	if uid == 0 || len(token) == 0 {
		logger.Error("user login error uid=%v token=%v", uid, token)
		mybuf.Code = config.INVALID
		if mybuf.WriteToByConn(conn, nil) != config.OK {
			CleanClient(fd)
		}
		return
	}
	if !gate_config.CONF.DEV_ENV {
		// 获取customer表数据
		cst := db.Customer{
			Id: uid,
		}
		err := cst.GetTokenById()
		if err != nil {
			logger.Error("db error.")
			return
		}
		// log.Println(cst,token)
		if cst.Token != token {
			// token错误
			mybuf.Code = config.PARAMERROR
			if mybuf.WriteToByConn(conn, nil) != config.OK {
				CleanClient(fd)
			}
			return
		}
	}
	//logger.Info("Login uid = %d token = %s", uid, token)
	db_user := sharedb.User{
		Id: uid,
	}
	err = db_user.GetByModel(db.Conn)
	if err != nil {
		logger.Error("%v", err)
		return
	}
	eps := &myepoll.Eps
	// 本机查询缓存是否还在
	*shm_user = sharemem.GetUserByMapUid(uid)
	if *shm_user != nil {
		// 缓存还在 更新session
		old_fd := (*shm_user).Fd
		if !(*shm_user).Get_user_by_index(uid, fd) {
			sharemem.DeleteUserMap(uid)
			*shm_user = nil
		} else {
			if old_fd > 0 && old_fd != fd {
				//通知老连接已被踢 session必过期 不用断连接
				tmpbuf := mysock.Create()
				tmpbuf.Command = config.SC_Kick_User
				tmpbuf.ForwardWithNewSession(old_fd, 0)
			}
		}
	}
	if *shm_user == nil {
		// new共享内存user
		*shm_user = sharemem.Create_user_by_id(uid, fd)
		if *shm_user == nil {
			mybuf.Code = config.FULL
			if mybuf.WriteToByConn(conn, nil) != config.OK {
				CleanClient(fd)
			}
			return
		}
		//logger.Info("create index = %d Session = %d", (*shm_user).Index, (*shm_user).Session)
	}
	// 选择logic server
	//logger.Info("Lserver = %d", (*shm_user).Lserver)
	server_id := (*shm_user).Lserver
	if server_id == 0 {
		server_id = db_user.Server
	}

	if server_id == 0 {
		stock := int32(0)
		for k, v := range eps.GetServerMapByType(myepoll.CONN_TYPE_LOGIC) {
			if v.Stock > stock {
				stock = v.Stock
				fd = v.Fd
				server_id = k
			}
		}
	}

	// 指定服务器id强登 内网调试
	if createreq.ServerId != 0 && gate_config.CONF.DEV_ENV {
		server_id = int16(createreq.ServerId)
	}

	// 转发到logic
	mybuf.ServerForwardWithNewSession(myepoll.CONN_TYPE_LOGIC,server_id, uint64(uid))
}
